package app.server.project.main.service.service.auth.solana;


import cn.hutool.core.codec.Base58;
import org.springframework.stereotype.Service;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Service
public class SolanaWalletValidator {

    /**
     * 解码Solana Base58编码的公钥
     *
     * @param publicKey Base58编码的公钥
     * @return 公钥字节数组
     */
    private byte[] decodeSolanaPublicKey(String publicKey) throws Exception {
        // 这里需要引入Base58解码库，如bitcoinj或自实现
        // 示例使用伪代码表示
        return Base58.decode(publicKey);
    }

    /**
     * 验证Solana钱包签名登录
     *
     * @param publicKey Base58编码的公钥
     * @param signature Base64编码的签名
     * @param message   签名的消息内容
     * @return 验证是否成功
     */
    public boolean validateSolanaLogin(String publicKey, String signature, String message) {
        try {
            // 将Solana公钥(Base58)转换为标准格式
            byte[] publicKeyBytes = decodeSolanaPublicKey(publicKey);

            // 解码Base64签名
            byte[] signatureBytes = Base64.getDecoder().decode(signature);

            // 获取消息字节
            byte[] messageBytes = message.getBytes("UTF-8");

            // 使用Ed25519算法验证签名
            Signature sig = Signature.getInstance("Ed25519");
            PublicKey pubKey = KeyFactory.getInstance("Ed25519")
                    .generatePublic(new X509EncodedKeySpec(publicKeyBytes));

            sig.initVerify(pubKey);
            sig.update(messageBytes);

            return sig.verify(signatureBytes);
        } catch (Exception e) {
            return false;
        }
    }
}
